﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel.Description;
using System.ServiceModel.Dispatcher;
using System.Text;
using Spike.ServiceFramework.ServiceModel.Audit;
using System.Diagnostics;
using System.ServiceModel;

using Spike.ServiceFramework.ServiceModel.Registration;

namespace Spike.ServiceFramework.ServiceModel
{
    public class ClientMessageInspector : IClientMessageInspector, IEndpointBehavior
    {
        public ClientMessageInspector(ClientBehaviorExtension behavior)
        {
            Behavior = behavior;
        }

        protected ClientBehaviorExtension Behavior { get; set; }
        protected bool ShouldAudit { get { return Behavior.Audit != null; } }
        protected bool ApplyRegistration { get { return Behavior.Registration != null; } }
        
        public void AddBindingParameters(ServiceEndpoint endpoint, System.ServiceModel.Channels.BindingParameterCollection bindingParameters) { }
        public void Validate(ServiceEndpoint endpoint) { }


        void IClientMessageInspector.AfterReceiveReply(ref System.ServiceModel.Channels.Message reply, object correlationState)
        {
            if (ShouldAudit)
            {
                Behavior.Audit.CompleteClientTraceRecord(ref reply, correlationState);
            }
        }

        object IClientMessageInspector.BeforeSendRequest(ref System.ServiceModel.Channels.Message request, System.ServiceModel.IClientChannel channel)
        {
            if (ApplyRegistration)
                Behavior.Registration.ApplyRegistration(request);

            if (ShouldAudit)
                return Behavior.Audit.CreateClientTraceRecord(ref request, channel);

            return null;
        }

        public void ApplyDispatchBehavior(ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher)
        {
            
        }

        public void ApplyClientBehavior(ServiceEndpoint endpoint, ClientRuntime clientRuntime)
        {
            clientRuntime.MessageInspectors.Add(this);
        }
    }
}
